<?php

namespace app\admin\service;

use app\admin\model\UM as UM;
use app\admin\traits\AdminCheckTrait;
use app\common\model\AccountBill;
use app\common\model\Member;
use think\exception\ValidateException;

/**
 * Class TransactionMarginService
 * @package app\admin\service
 */
class TransactionMarginService extends TransactionService
{
    use AdminCheckTrait;

    /**
     * 列表
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function indexMargin(UM $user, $memberId, $startTime, $endTime, ?int $page = null, ?int $page_size = null): array
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->transactionDao->listTransactionMargin($memberId, $startTime, $endTime, $page, $page_size);
    }

    /**
     * 新增
     * @param UM $user
     * @param array $params
     * @return  void
     */
    public function addMargin(UM $user, array $params): void
    {
        $userId = $user->id;
        $memberId = $params['memberId'] ?? null;
        $describe = $params['describe'] ?? null;
        $total = $params['total'] ?? null;

        $this->checkAdmin($user);

        $fromId = $memberId;
        $fromType = AccountBill::MEMBER;

        $member = Member::where('id', $memberId)->whereIn('status', [0, 1])->find();
        if (!$member) {
            throw new ValidateException('该用户不存在或已被删除');
        }

        $name = '保证金';
        $accountType = PAYMENT_MARGIN;
        $billType = TRADE_OFFLINE_MARGIN_RECHARGE;

        $this->handle($total, $describe, $userId, $memberId, $fromType, $fromId, $name, $accountType, $billType);
    }

    /**
     *
     * @param $total
     * @param $describe
     * @param $userId
     * @param $memberId
     * @param $fromType
     * @param $fromId
     * @param string $name
     * @param $accountType
     * @param $billType
     * @return void
     */
    private function handle($total, $describe, $userId, $memberId, $fromType, $fromId, string $name, $accountType, $billType): void
    {
        // 到账金额
        if (!is_numeric($total)) {
            throw new ValidateException('请输入正确的' . $name . '数量');
        }
        $total = round($total, 2);
        $amount = $total;

        // 备注
        if (is_blank($describe)) {
            throw new ValidateException('请输入备注信息');
        }

        // 校验
        if (bccomp($total, 0, 2) === 0) {
            throw new ValidateException($name . '到账数量不能为0');
        }

        $this->handleTransfer($amount, $total, $describe, $userId, 0, $memberId, $accountType, $fromType, $fromId, $billType);
    }

}
